package com.czhappy.huans.controller;

import com.czhappy.huans.Utils.ToolUtil;
import com.czhappy.huans.entity.Kaoqin;
import com.czhappy.huans.entity.KaoqinRecord;
import com.czhappy.huans.entity.User;
import com.czhappy.huans.excel.ExcelConstant;
import com.czhappy.huans.excel.ExcelData;
import com.czhappy.huans.excel.ExcelUtils;
import com.czhappy.huans.exception.Result;
import com.czhappy.huans.exception.ResultUtil;
import com.czhappy.huans.service.KaoqinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/kaoqin")
public class KaoqinContoller {

    private int tjYear = 2019;
    private int tjMonth = 6;
    private String swsbsj = "08:00";
    private String swxbsj = "12:00";
    private String xwsbsj = "14:30";
    private String xwxbsj = "17:30";
    private int minuxMinute = -1*60;

    @Autowired
    private KaoqinService kaoqinService;

    @RequestMapping(value = "/export", method = RequestMethod.POST)
    private Result exportKaoqin(Integer type) throws Exception {
        if(ToolUtil.isEmpty(type)){
            type=0;
        }
        List<User> userInfoList = kaoqinService.queryUserNameList(type);
        if(userInfoList!=null) {
            List<KaoqinRecord> recordList = new ArrayList<>();
            int tempXh = 1;
            for (User user : userInfoList) {
                String userName = user.getUserName();
                if(ToolUtil.isNotEmpty(userName)) {
                    int year = tjYear;
                    int month = tjMonth;
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(year, month, 0); //输入类型为int类型
                    int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
                    System.out.println(userName+"："+year + "年" + month + "月有" + dayOfMonth + "天");

                    for (int i = 1; i <= dayOfMonth; i++) {
                        String nyr = year + "" + (month > 9 ? month : ("0" + month)) + "" + (i > 9 ? i : ("0" + i));
                        //上午
                        KaoqinRecord record1 = new KaoqinRecord();
                        record1.setXh(tempXh + "");
                        record1.setKqhm(user.getKqCode());
                        record1.setZdybh("");
                        record1.setXm(userName);
                        record1.setSfznpb("");
                        record1.setRq(year + "/" + month + "/" + i);
                        record1.setDysd("上午");
                        record1.setSbsj(swsbsj);
                        record1.setXbsj(swxbsj);
                        record1.setNyr(nyr);
                        recordList.add(record1);

                        //下午
                        KaoqinRecord record2 = new KaoqinRecord();
                        record2.setXh(tempXh + "");
                        record2.setKqhm(user.getKqCode());
                        record2.setZdybh("");
                        record2.setXm(userName);
                        record2.setSfznpb("");
                        record2.setRq(year + "/" + month + "/" + i);
                        record2.setDysd("下午");
                        record2.setSbsj(xwsbsj);
                        record2.setXbsj(xwxbsj);
                        record2.setNyr(nyr);
                        recordList.add(record2);

                    }
                    //计算上班、下班时间
                    List<Kaoqin> kaoqinList = kaoqinService.queryKaoqinListByName(userName);
                    if (kaoqinList != null) {
                        for (KaoqinRecord record : recordList) {
                            for (Kaoqin kaoqin : kaoqinList) {
                                if (ToolUtil.isNotEmpty(kaoqin.getClockTime()) && record.getXm().equals(kaoqin.getUserName())) {
                                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                                    SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm");
                                    String tempDateStr = sdf1.format(kaoqin.getClockTime());
                                    if (record.getNyr().equals(tempDateStr)) {//同一天
                                        if ("上午".equals(record.getDysd())) {
                                            String tempswStr = record.getNyr() + " " + swxbsj + ":00";
                                            Date tempswDate = sdf2.parse(tempswStr);
                                            String tempzwStr = record.getNyr() + " " + xwsbsj + ":00";
                                            Date tempzwDate = sdf2.parse(tempzwStr);
                                            String tempxwStr = record.getNyr() + " " + xwxbsj + ":00";
                                            Date tempxwDate = sdf2.parse(tempxwStr);
                                            if (kaoqin.getClockTime().compareTo(tempswDate) <= 0) {//上午签到
                                                if (ToolUtil.isEmpty(record.getQdsj())) {//取最早的那次打卡
                                                    Calendar xddkTime = Calendar.getInstance();
                                                    xddkTime.setTime(kaoqin.getClockTime());
                                                    //特殊需求6月10号作息时间调整
                                                    int day = xddkTime.get(Calendar.DATE);//获取日
                                                    int hours = xddkTime.get(Calendar.HOUR_OF_DAY);       //获取当前小时
                                                    System.out.println("day=" + day + "，hours="+hours);
                                                    if(hours>4) {//五点之前就不要减了（针对凌晨打卡的）
                                                        if (day < 10) {//10号之前减30分钟
                                                            xddkTime.add(Calendar.MINUTE, -30);//差值分钟前的时间
                                                        } else {
                                                            xddkTime.add(Calendar.MINUTE, minuxMinute);//差值分钟前的时间
                                                        }
                                                    }
                                                    //xddkTime.add(Calendar.MINUTE, minuxMinute);//差值分钟前的时间
                                                    record.setQdsj(sdf3.format(xddkTime.getTime()));
                                                }
                                            } else if (kaoqin.getClockTime().compareTo(tempzwDate) <= 0) {//上午签退
                                                record.setQtsj(sdf3.format(kaoqin.getClockTime()));
                                            } else if (kaoqin.getClockTime().compareTo(tempxwDate) <= 0) {//上午签退（中午迟到打卡）
                                                if (ToolUtil.isEmpty(record.getQtsj())) {
                                                    kaoqin.isCalculated = true;//该打卡已使用，避免excel中出现相同的打卡
                                                    record.setQtsj(sdf3.format(kaoqin.getClockTime()));
                                                }
                                            }
                                        } else if ("下午".equals(record.getDysd())) {
                                            String tempxwStr = record.getNyr() + " " + xwsbsj + ":00";
                                            Date tempxwDate = sdf2.parse(tempxwStr);
                                            if (!kaoqin.isCalculated && kaoqin.getClockTime().compareTo(tempxwDate) > 0) {//上午签退
                                                record.setQtsj(sdf3.format(kaoqin.getClockTime()));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    tempXh++;
                }
            }
            System.out.println("recordList.size()="+recordList.size());
            //导出excel
            ExcelData data = new ExcelData();
            data.setName(tjYear + "年" + tjMonth + "月考勤");
            List<String> titles = new ArrayList();
            titles.add("序号");
            titles.add("考勤号码");
            titles.add("自定义编号");
            titles.add("姓名");
            titles.add("是否智能排班");
            titles.add("日期");
            titles.add("对应时段");
            titles.add("上班时间");
            titles.add("下班时间");
            titles.add("签到时间");
            titles.add("签退时间");
            data.setTitles(titles);

            List<List<Object>> rows = new ArrayList();
            for(KaoqinRecord record : recordList){
                List<Object> row = new ArrayList();
                row.add(record.getXh());
                row.add(record.getKqhm());
                row.add(record.getZdybh());
                row.add(record.getXm());
                row.add(record.getSfznpb());
                row.add(record.getRq());
                row.add(record.getDysd());
                row.add(record.getSbsj());
                row.add(record.getXbsj());
                row.add(record.getQdsj());
                row.add(record.getQtsj());
                rows.add(row);
            }
            data.setRows(rows);
            String rangeName = "";
            if(type==1){
                rangeName = "（安立德新）";
            }else if(type==2){
                rangeName = "（同济）";
            }
            String fileName = tjYear + "年" + tjMonth + "月考勤" + rangeName + System.currentTimeMillis() + ".xlsx";
            int rowTotal = ExcelUtils.generateExcel(data, ExcelConstant.FILE_PATH + fileName);
            System.out.println("合计："+rowTotal);
            return ResultUtil.success(recordList);
        }
        return ResultUtil.error();
    }
}
